<template>
    <div class="primitive-merge">
        <h3>Primitive几何形体合并</h3>
        <div class="merge-info">
            <p><strong>说明：</strong>将多个GeometryInstance合并到单个Primitive中可显著提高性能</p>
            <p>合并后的Primitive可以统一管理，减少CPU负担，更好利用GPU</p>
        </div>
        <div class="merge-controls">
            <button @click="createColorfulRectangles" class="merge-btn">多彩矩形球体</button>
            <button @click="createMultiEllipsoids" class="merge-btn">多椭球体实例</button>
            <button @click="createRandomShapes" class="merge-btn">随机形状合并</button>
            <button @click="clearMergedPrimitives" class="clear-btn">清除合并对象</button>
        </div>
        <div class="merge-status">
            <p v-if="mergedCount > 0">已创建 {{ mergedCount }} 个合并Primitive</p>
            <p v-if="totalInstances > 0">包含 {{ totalInstances }} 个几何实例</p>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, inject, onMounted } from 'vue';
import { XbsjEarthUi } from '../../../../scripts/xbsjEarthUi';
import PrimitiveManager from './primitiveManager';

const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi;
const mergedCount = ref(0);
const totalInstances = ref(0);
const primitiveManager = PrimitiveManager.getInstance();

// 获取EarthUI中的Cesium原生Viewer实例
const getCesiumViewer = () => {
    return xbsjEarthUi.activeViewer?.innerViewer?.viewer;
};

// 创建多彩矩形球体（参考课本图5.2）
const createColorfulRectangles = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer) return;

    try {
        const instances = [];
        
        // 创建2592个矩形覆盖整个地球表面（参考课本）
        // 经度：-180到180度，每5度一个矩形，共72个
        // 纬度：-90到90度，每5度一个矩形，共36个
        // 总计：72 * 36 = 2592个矩形
        for (let lon = -180.0; lon < 180.0; lon += 5.0) {
            for (let lat = -90.0; lat < 90.0; lat += 5.0) {
                const instance = new (window as any).Cesium.GeometryInstance({
                    geometry: new (window as any).Cesium.RectangleGeometry({
                        rectangle: (window as any).Cesium.Rectangle.fromDegrees(lon, lat, lon + 5.0, lat + 5.0),
                        vertexFormat: (window as any).Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT
                    }),
                    attributes: {
                        color: (window as any).Cesium.ColorGeometryInstanceAttribute.fromColor(
                            (window as any).Cesium.Color.fromRandom({ alpha: 0.5 })
                        )
                    }
                });
                instances.push(instance);
            }
        }

        const primitive = new (window as any).Cesium.Primitive({
            geometryInstances: instances,
            appearance: new (window as any).Cesium.PerInstanceColorAppearance()
        });

        viewer.scene.primitives.add(primitive);
        primitiveManager.addPrimitive(primitive); // 添加到全局管理器
        mergedCount.value++;
        totalInstances.value += instances.length;
        console.log(`多彩矩形球体创建成功，包含 ${instances.length} 个矩形`);
    } catch (error) {
        console.error('创建多彩矩形球体失败:', error);
    }
};

// 创建多椭球体实例
const createMultiEllipsoids = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer) return;

    try {
        const ellipsoidGeometry = new (window as any).Cesium.EllipsoidGeometry({
            radii: new (window as any).Cesium.Cartesian3(100000.0, 100000.0, 100000.0),
            vertexFormat: (window as any).Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
        });

        const instances = [];
        const colors = [
            (window as any).Cesium.Color.RED,
            (window as any).Cesium.Color.GREEN,
            (window as any).Cesium.Color.BLUE,
            (window as any).Cesium.Color.YELLOW,
            (window as any).Cesium.Color.PURPLE,
            (window as any).Cesium.Color.CYAN
        ];

        // 创建6个不同颜色的椭球体（中国主要城市）
        const cities = [
            { lon: 116.0, lat: 40.0, name: '北京' },
            { lon: 121.0, lat: 31.0, name: '上海' },
            { lon: 113.0, lat: 23.0, name: '广州' },
            { lon: 104.0, lat: 30.0, name: '成都' },
            { lon: 108.0, lat: 34.0, name: '西安' },
            { lon: 120.0, lat: 30.0, name: '杭州' }
        ];

        for (let i = 0; i < 6; i++) {
            const city = cities[i];
            const height = i * 200000;

            const instance = new (window as any).Cesium.GeometryInstance({
                geometry: ellipsoidGeometry,
                modelMatrix: (window as any).Cesium.Matrix4.multiplyByTranslation(
                    (window as any).Cesium.Transforms.eastNorthUpToFixedFrame(
                        (window as any).Cesium.Cartesian3.fromDegrees(city.lon, city.lat)
                    ),
                    new (window as any).Cesium.Cartesian3(0.0, 0.0, height),
                    new (window as any).Cesium.Matrix4()
                ),
                attributes: {
                    color: (window as any).Cesium.ColorGeometryInstanceAttribute.fromColor(colors[i])
                }
            });
            instances.push(instance);
        }

        const primitive = new (window as any).Cesium.Primitive({
            geometryInstances: instances,
            appearance: new (window as any).Cesium.PerInstanceColorAppearance({
                translucent: false,
                closed: true
            })
        });

        viewer.scene.primitives.add(primitive);
        primitiveManager.addPrimitive(primitive); // 添加到全局管理器
        mergedCount.value++;
        totalInstances.value += instances.length;
        console.log(`多椭球体实例创建成功，包含 ${instances.length} 个椭球体`);
    } catch (error) {
        console.error('创建多椭球体实例失败:', error);
    }
};

// 创建随机形状合并
const createRandomShapes = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer) return;

    try {
        const instances = [];
        
        // 创建随机位置的圆形（中国范围内）
        for (let i = 0; i < 20; i++) {
            const longitude = 110 + Math.random() * 15; // 中国经度范围
            const latitude = 20 + Math.random() * 25;  // 中国纬度范围
            const radius = 50000 + Math.random() * 100000;

            const circleGeometry = new (window as any).Cesium.CircleGeometry({
                center: (window as any).Cesium.Cartesian3.fromDegrees(longitude, latitude),
                radius: radius,
                vertexFormat: (window as any).Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
            });

            const instance = new (window as any).Cesium.GeometryInstance({
                geometry: circleGeometry,
                attributes: {
                    color: (window as any).Cesium.ColorGeometryInstanceAttribute.fromColor(
                        (window as any).Cesium.Color.fromRandom({ alpha: 0.7 })
                    ),
                    show: (window as any).Cesium.ShowGeometryInstanceAttribute(true)
                },
                id: `circle-${i}`
            });
            instances.push(instance);
        }

        const primitive = new (window as any).Cesium.Primitive({
            geometryInstances: instances,
            appearance: new (window as any).Cesium.PerInstanceColorAppearance({
                translucent: true,
                closed: false
            })
        });

        viewer.scene.primitives.add(primitive);
        primitiveManager.addPrimitive(primitive); // 添加到全局管理器
        mergedCount.value++;
        totalInstances.value += instances.length;
        console.log(`随机形状合并创建成功，包含 ${instances.length} 个圆形`);
    } catch (error) {
        console.error('创建随机形状合并失败:', error);
    }
};

// 清除合并的Primitive
const clearMergedPrimitives = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer) return;

    try {
        // 只清除全局管理器中的Primitive
        primitiveManager.clearAllPrimitives(viewer);
        mergedCount.value = 0;
        totalInstances.value = 0;
        console.log('合并Primitive已清除');
    } catch (error) {
        console.error('清除合并Primitive失败:', error);
    }
};

onMounted(() => {
    // 组件加载时检查现有Primitive数量
    const viewer = getCesiumViewer() as any;
    if (viewer) {
        mergedCount.value = viewer.scene.primitives.length;
        // 计算总实例数
        let total = 0;
        for (let i = 0; i < viewer.scene.primitives.length; i++) {
            const primitive = viewer.scene.primitives.get(i);
            if (primitive.geometryInstances) {
                total += primitive.geometryInstances.length;
            }
        }
        totalInstances.value = total;
    }
});
</script>

<style scoped>
.primitive-merge {
    width: 280px;
    box-sizing: border-box;
    padding: 10px;
}

.merge-info {
    box-sizing: border-box;
    font-size: 14px;
    padding: 10px;
    background-color: #000000;
    border-radius: 4px;
    margin-bottom: 15px;
}

.merge-controls {
    display: flex;
    flex-direction: column;
    margin-bottom: 15px;
}

.merge-btn, .clear-btn {
    margin-bottom: 8px;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.merge-btn {
    background-color: #4CAF50;
    color: white;
}

.merge-btn:hover {
    background-color: #45a049;
}

.clear-btn {
    background-color: #f44336;
    color: white;
}

.clear-btn:hover {
    background-color: #d32f2f;
}

.merge-status {
    padding: 10px;
    background-color: #000000;
    border-radius: 4px;
    border-left: 4px solid #4CAF50;
    color: #4CAF50;
    font-weight: bold;
}
</style>
